<template>
	<view class="main">
    <view class="content">
      <u--form
          labelPosition="left"
          :model="merchantDetail"
          :rules="bankCardInfoModelRules"
          ref="bankCardInfoForm"
          labelWidth="90"
          :labelStyle="{fontSize:'28rpx', color: 'rgba(0, 0, 0, 0.7)', padding: '18rpx 0'}"
      >
        <view class="content-item">
          <view class="content-title">上传结算信息</view>
          <u-form-item label=" " prop="bankCardAB" borderBottom ref="bankCardItem" labelWidth="0"
                       v-if="merchantDetail.accountType != accountTypeEnum.CORPORATE_ACCOUNT">
            <view class="upload u-flex u-row-between">
              <u-upload
                  ref="bankCardAUpload"
                  :fileList="bankCardAUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.bankCardA"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.bankCardA)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/debit-card-A.png`"
                          :width="imgWidth" :height="imgHeight"/>
              </u-upload>

              <u-upload
                  ref="bankCardBUpload"
                  :fileList="bankCardBUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.bankCardB"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.bankCardB)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/debit-card-B.png`"
                          :width="imgWidth" :height="imgHeight"/>
              </u-upload>
            </view>
          </u-form-item>
          <u-form-item label="银行卡号" prop="bankCardNo" borderBottom ref="bankCardNoItem">
            <u--input border="none" type="number" placeholder="请输入银行卡号" inputAlign="left" clearable fontSize="13" maxlength="32"
                      v-model="merchantDetail.bankCardNo"/>
          </u-form-item>
          <u-form-item label="银行名称" prop="bankName" borderBottom ref="bankNameItem">
            <u--input border="none" placeholder="请输入银行名称（如:中国建设银行）" inputAlign="left" clearable fontSize="13" maxlength="30"
                      v-model="merchantDetail.bankName"/>
          </u-form-item>
          <u-form-item label="账户户名" prop="bankCertName" borderBottom ref="bankCertNameItem">
            <u--input border="none" placeholder="请输入账户户名" inputAlign="left" clearable fontSize="13" maxlength="30"
                      v-model="merchantDetail.bankCertName"/>
          </u-form-item>
          <u-form-item label="开户地区" prop="bankRegion" borderBottom ref="bankRegionItem" rightIcon="" @click="openBankRegion()">
            <u--input border="none" placeholder="请选择开户地区" inputAlign="left" clearable fontSize="13" :disabled="true" disabledColor="#fff"
                      v-model="merchantDetail.bankRegion"/>
            <u-icon
                slot="right"
                name="arrow-right"
            ></u-icon>
          </u-form-item>
          <u-form-item label="联行号" prop="contactLine" borderBottom ref="contactLineItem">
            <u--input border="none" type="number" placeholder="请输入联行号" inputAlign="left" clearable fontSize="13" maxlength="32"
                      v-model="merchantDetail.contactLine"/>
          </u-form-item>
          <u-form-item label="商户收款简称" prop="merchantShortName" ref="merchantShortNameItem">
            <u--input border="none" placeholder="请输入商户收款简称" inputAlign="left" clearable fontSize="13" maxlength="32"
                      v-model="merchantDetail.merchantShortName"/>
          </u-form-item>
          <u-form-item label="支付渠道" prop="payCompanyName" ref="paymentChannelItem" @click="open()">
            <u--input border="none" type="number" inputAlign="left" clearable fontSize="13" maxlength="32"
                      :disabled="true" placeholder="请选择支付渠道" disabledColor="#fff"
                      v-model="merchantDetail.payCompanyName" />
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>

          <pick-bank-region ref="pickBankRegion" :pickerValueDefault="cityPickerValueDefault" @onConfirm="onConfirm" themeColor="#007AFF"/>

        </view>
      </u--form>

      <view class="footer">
        <u-button type="primary" text="添加商户" :customStyle="editBtnCustomStyle" @click="submit()"/>
      </view>
    </view>

		<u-popup :show="payCompanyPopupShow" round="20rpx" mode="bottom" @close="close" @open="open">
			<view class="payment-choice">
				<view class="radio-choice">
					<u-radio-group placement="column" iconPlacement="right">
						<u-radio activeColor="#6072FF" :customStyle="{marginBottom: '80rpx'}" v-for="(item, index) in payCompanyList" :key="index"
							:label="item.name" :name="item" @change="payCompanyRadioChange">
						</u-radio>
					</u-radio-group>
				</view>
			</view>
		</u-popup>
    <bankCardAComponent ref="bankCardAComponentRef"/>
	</view>
</template>

<script>
import merchantDetail from '@/common/po/merchant-detail.ts';
import bankCardAComponent from '@/pages-qualification/base-info/bank-card-A';
	export default {
    components: {
      bankCardAComponent,
    },
		data() {
			return {
        qiNiuImgURL: this.$configPath.qiNiuImgURL,
        baseStaticFileUrl: this.$configPath.staticFileUrl,

        editBtnCustomStyle: {
          width: '690rpx',
          height: '88rpx',
          borderRadius: '120rpx',
          color: '#fff',
          margin: '14rpx auto 0rpx',
        },

        merchantDetail: merchantDetail,

        cityPickerValueDefault: [0, 0],

        maxSize: 3 * 1024 * 1024,
        imgWidth: '330rpx',
        imgHeight: '234rpx',
        merchantTypeEnum: this.$merchantTypeEnum,
        accountTypeEnum: this.$accountTypeEnum,

        bankCardAUrlList: [],
        bankCardBUrlList: [],

        photoTypeEnum: {
          bankCardA: 'bankCardA',
          bankCardB: 'bankCardB',
        },

        bankCardAB: {
          type: 'boolean',
          required: true,
          message: '请上传银行卡正、反面照片',
          validator: (rule, value, callback) => {
            return value == true;
          },
        },

        bankCardInfoModelRules: {
          'bankCardNo': {
            type: 'string',
            required: true,
            message: '请输入银行卡号',
            max: 32,
            min: 8,
            trigger: ['blur'],
          },
          'bankName': {
            type: 'string',
            required: true,
            message: '请输入结算名称',
            max: 30,
            min: 4,
            trigger: ['blur'],
          },
          'bankCertName': {
            type: 'string',
            required: true,
            message: '请输入账户户名',
            max: 30,
            min: 2,
            trigger: ['blur'],
          },
          'bankRegion': {
            type: 'string',
            required: true,
            message: '请选择开户支行所在地',
          },
          'contactLine': {
            type: 'integer',
            required: true,
            message: '请输入联行号',
            max: 30,
            min: 6,
            trigger: ['blur'],
          },
          'merchantShortName': {
            type: 'string',
            required: true,
            message: '请输入2至10位的商户收款简称，并且不能纯数字或纯字母',
            max: 20,
            min: 2,
            trigger: ['blur'],
          },
          'payCompanyName': {
            type: 'string',
            required: true,
            message: '请选择支付渠道',
            max: 30,
            min: 1,
            trigger: ['blur'],
          },
        },
        // 账户类型
        accountTypeList: [],
        merchantInfoUploadStateEnum: this.$merchantInfoUploadStateEnum,
        payCompanyList: [],
        payCompanyPopupShow: false,

        // 资质资料
        qualificationData: {
          id: '',
          certNo: '',
        },

			}
		},
		onLoad(options) {
			const qualificationData = JSON.parse(decodeURIComponent(options.qualification));
			// console.log("this.qualificationData", this.qualificationData)

			if (this.$u.test.isEmpty(qualificationData.id) || this.$u.test.isEmpty(qualificationData.certNo)) {
        getApp().err('资质信息获取不成功，请重新进入页面');
        return
			}

			this.qualificationData.id = qualificationData.id;
      this.qualificationData.certNo = qualificationData.certNo;

      this.findQualificationInfo()
      this.findPayCompany();
		},
		onReady() {
			this.$refs.bankCardInfoForm.setRules(this.bankCardInfoModelRules)
		},
		methods: {
      initData(data){
        this.merchantDetail = data;

        if (this.accountTypeEnum.CORPORATE_ACCOUNT != this.merchantDetail.accountType){
          // 结算类型不为对公时才对结算卡正反面校验是否上传
          this.bankCardInfoModelRules['bankCardAB'] = this.bankCardAB;
        }

        // 结算卡正面
        if (!this.$u.test.isEmpty(this.merchantDetail.bankCardA)){
          this.bankCardAUrlList.length = 0;
          this.bankCardAUrlList.push({
            status: 'success',
            message: '',
            url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.bankCardA)
          })
        }
        // 结算卡反面
        if (!this.$u.test.isEmpty(this.merchantDetail.bankCardB)){
          this.bankCardBUrlList.length = 0;
          this.bankCardBUrlList.push({
            status: 'success',
            message: '',
            url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.bankCardB)
          })
        }

        // 校验结算卡正反面是否都上传
        this.checkBankCard();
      },

      submit(){
        this.$refs.bankCardInfoForm.validate().then(res => {
          let reg = new RegExp(/^(?:[0-9A-Za-z]|[\x81-\xfe].)+$/);

          if (reg.test(this.merchantDetail.merchantShortName)) {
            this.merchantDetail.merchantShortName = '';
            this.merchantShortNameValidateField();
            return
          }

          this.addMerchant();
        }).catch(error => {
          console.error(error)
          getApp().err('请按红色文字提示输入完整信息才能提交修改')
        })
      },

      addMerchant(){
        uni.showModal({
          title: '温馨提示',
          content: "如果您的商户可以正常使用或未认证请勿继续签约其他渠道。因为签约后90天内无交易将会自动关闭支付权限并且消耗一个永久支付权限名额（每个资质在每个渠道的支付权限名额有限）",
          cancelText: "确定申请",
          confirmText: "取消",
          success: (res) => {
            if (!res.confirm) {
              uni.showLoading({
                title: '提交中...',
                mask: true
              })

              this.$api('qualification.qualificationRegister', this.merchantDetail).then(res => {
                uni.hideLoading();
                if (res.status == 0) {
                  this.$helpers.toast('提交成功，请耐心等待审核', 'none', 4000, true, () => {
                    uni.switchTab({
                      url: '/pages/home/home',
                      success (){
                        uni.navigateTo({
                          url: '/pages-merchant/list/list'
                        })
                      }
                    })
                  });
                } else {
                  getApp().err("提交不成功：" + res.msg);
                }
              }).catch(() => {
                uni.hideLoading();
              });
            }
          }
        })
      },

      // 结算卡 正面重新上传
      bankCardAUploadAgain(){
        this.bankCardAUrlList.splice(0, 1);
        this.$nextTick(() => {
          this.$refs.bankCardAUpload.chooseFile()
        })
      },

      openBankRegion(){
        if (this.accountTypeEnum.CORPORATE_ACCOUNT != this.merchantDetail.accountType && this.$u.test.isEmpty(this.merchantDetail.bankCardA)){
          getApp().err('操作该功能前请先上传银行卡正面');
          this.bankCardABValidateField();
          return
        }

        if (this.$u.test.isEmpty(this.merchantDetail.bankName)){
          getApp().err('操作该功能前请先输入银行卡银行名称');
          this.bankNameValidateField();
          return
        }

        if (this.$u.test.isEmpty(this.merchantDetail.bankCardNo)){
          getApp().err('操作该功能前请先输入银行卡号');
          this.bankCardNoValidateField();
          return
        }

        this.$refs.pickBankRegion.open();
      },

      onConfirm(e) {
        // console.log("e", e)
        this.merchantDetail.bankRegion = e.label;
        this.merchantDetail.bankProvince = e.provinceCode;
        this.merchantDetail.bankCity = e.cityCode;

        let bankUnionCode = {
          bankName: this.merchantDetail.bankName,
          bankCardNo: this.merchantDetail.bankCardNo,
          bankProvince: e.labelArr[0],
          bankCity: e.labelArr[1],
          accountType: this.merchantDetail.accountType,
        }
        this.getBankUnionCodeBy(bankUnionCode);
        this.bankRegionValidateField();
      },

      // 获取联行号
      getBankUnionCodeBy(bankUnionCode) {
        this.$api('bankUnionCode.getBankUnionCodeBy', bankUnionCode).then(res => {
          if (res.status == 0){
            if (!this.$u.test.isEmpty(res.data) && !this.$u.test.isEmpty(res.data.contactLine)){
              this.merchantDetail.contactLine = res.data.contactLine
              this.contactLineValidateField();
            }
          }
        })
      },

      deletePhoto(photoType){
        try {
          if (photoType == this.photoTypeEnum.bankCardA){
            this.merchantDetail.bankCardA = "";
            this.merchantDetail.bankCardNo = "";
            this.bankCardAUrlList.splice(0, 1)
          } else if (photoType == this.photoTypeEnum.bankCardB){
            this.merchantDetail.bankCardB = "";
            this.bankCardBUrlList.splice(0, 1)
          } else {
            getApp().err("图片类型有误")
          }
          this.checkBankCard(true);
        } catch (e){
          console.error(e.toString())
          getApp().err("删除不成功");
        }
      },

      async photoUploadAfterRead(event) {
        uni.showLoading({
          title: '上传中',
          mask: true
        })

        const item = {
          url: event.file.url,
          status: 'uploading',
          message: '上传中'
        }

        if (event.name == this.photoTypeEnum.bankCardA){
          this.bankCardAUrlList.push(item);

          this.photoUploadFilePromise(event.file.url, this.$photoTypeEnum.BANK_CARD_A).then((res) => {
            this.merchantDetail.bankCardA = res.data.picture;

            const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
            this.bankCardAUrlList.splice(0, 1, Object.assign(item, {
              status: 'success',
              message: '',
              url: url
            }))

            this.merchantDetail.bankCardNo = res.data.bankCardNumber;
            this.checkBankCard(true);

            // 上传成功，识别失败
            if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == res.status) {
              // 调起识别失败提示，并将刚上传的图片展示给他看
              this.$refs.bankCardAComponentRef.showPopup(url);
            }

          }).catch((err) => {
            console.error("bankCardACatch", err)
            this.bankCardAUrlList.splice(0, 1);
          })
        } else if (event.name == this.photoTypeEnum.bankCardB){
          this.bankCardBUrlList.push(item);

          this.photoUploadFilePromise(event.file.url, null).then((res) => {
            this.merchantDetail.bankCardB = res.data.picture;

            const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
            this.bankCardBUrlList.splice(0, 1, Object.assign(item, {
              status: 'success',
              message: '',
              url: url
            }))

            this.checkBankCard(true);

          }).catch((err) => {
            console.error("bankCardBCatch", err)
            this.bankCardBUrlList.splice(0, 1);
          })
        } else {
          uni.hideLoading();
          getApp().err("e.name有误");
          return
        }
      },

      photoUploadFilePromise(fileUrl, photoType) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: this.$configPath.baseURL + '/api/merchant/merchantRegisterUploadByApplet',
            filePath: fileUrl,
            name: 'file',
            header: {
              Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
            },
            timeout: 6000,
            formData: {
              photoType: photoType
            },
            success: (res) => {
              uni.hideLoading();
              let data = JSON.parse(res.data);
              if (this.merchantInfoUploadStateEnum.SUCCESS == data.status) {
                this.$helpers.toast("上传成功", "success");
                resolve(data);
              } else if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == data.status){
                //上传成功，识别失败
                resolve(data);
              } else {
                reject(data)
                getApp().err("上传不成功，" + data.msg);
              }
            },
            fail: (res) => {
              uni.hideLoading();
              let errMsg = res.errMsg;
              if (uni.$u.test.contains(errMsg, 'timeout')) {
                errMsg = "请求超时，请重新上传";
              }
              getApp().err(errMsg);
              reject("请求超时，请重新上传")
            },
          });
        })
      },

      checkBankCard(checked){
        if (
            !this.$u.test.isEmpty(this.merchantDetail.bankCardA)
            && !this.$u.test.isEmpty(this.merchantDetail.bankCardB)
        ){
          this.merchantDetail.bankCardAB = true;
        } else {
          this.merchantDetail.bankCardAB = false;
        }

        if (checked){
          this.bankCardABValidateField();
          this.bankCardNoValidateField();
        }
      },

      bannerOversize() {
        getApp().err("图片大小超限，最大3MB。如图片来自相册，建议使用直接拍摄");
      },

      bankCardABValidateField(){
        this.$refs.bankCardInfoForm.validateField('bankCardAB', err => {
          // console.log("err", err)
        })
      },
      bankCardNoValidateField(){
        this.$refs.bankCardInfoForm.validateField('bankCardNo', err => {
          // console.log("err", err)
        })
      },
      bankNameValidateField(){
        this.$refs.bankCardInfoForm.validateField('bankName', err => {
          // console.log("err", err)
        })
      },
      bankRegionValidateField(){
        this.$refs.bankCardInfoForm.validateField('bankRegion', err => {
          // console.log("err", err)
        })
      },
      merchantShortNameValidateField(){
        this.$refs.bankCardInfoForm.validateField('merchantShortName', err => {
          // console.log("err", err)
        })
      },
      contactLineValidateField(){
        this.$refs.bankCardInfoForm.validateField('contactLine', err => {
          // console.log("err", err)
        })
      },
      payCompanyNameValidateField(){
        this.$refs.bankCardInfoForm.validateField('payCompanyName', err => {
          // console.log("err", err)
        })
      },

			// 查询资质信息
			findQualificationInfo() {

				this.$api('qualification.findQualificationInfo', this.qualificationData).then(res => {
					if (res.status == 0) {
					  this.initData(res.data)
					} else {
            getApp().err("查询资质不成功，" + res.msg);
          }
				}).catch(() => {
          uni.hideLoading();
        });
			},

			findPayCompany() {
				this.$api('merchantPayCompany.findPayCompany').then(res => {
					if(res.status == 0){
            this.payCompanyList.length = 0;
					  if (res.data.length > 0){
              res.data.forEach(item => {
                const payCompany = {
                  code: item.code,
                  name: item.name,
                }
                this.payCompanyList.push(payCompany)
              })
            }
					} else {
            getApp().err("查询渠道列表不成功，" + res.msg);
          }
				}).catch(() => {
          uni.hideLoading();
        });
			},

			open() {
				this.payCompanyPopupShow = true
			},

			close() {
				this.payCompanyPopupShow = false
			},

      payCompanyRadioChange(n) {
				console.log('radioChange', n);
				this.merchantDetail.payCompanyName = n.name;
        this.merchantDetail.payCompanyCode = n.code;
        this.$nextTick(()=>{
          this.payCompanyNameValidateField();
        })
        this.close();
			}
		}
	}
</script>

<style lang="scss" scoped>
.main{
  background-color: $uni-bg-color;

  .content{
    .content-item{
      margin-bottom: 20rpx;
      padding: 24rpx 30rpx;

      .content-title{
        color: rgb(13, 13, 13);
        font-size: 30rpx;
      }

      .upload{
        padding: 30rpx 0rpx 12rpx ;
      }
    }
  }

  .footer{
    width: 100%;
    margin-top: 94rpx;
    padding-bottom: 74rpx;
  }

  .payment-choice{
    padding: 30rpx;
  }
}

/deep/ .u-input__content__field-wrapper__field{
  width: 450rpx;
}

</style>
